package org.goodsmanager.service.impl;

import org.goodsmanager.entity.Order;
import org.goodsmanager.entity.OrderItem;
import org.goodsmanager.mapper.OrderMapper;
import org.goodsmanager.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Override
    @Transactional
    public Order createOrder(Order order, List<org.goodsmanager.entity.Cart> cartItems) {
        // 将购物车商品转换为订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (org.goodsmanager.entity.Cart cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(Long.valueOf(cartItem.getProductId()));
            orderItem.setProductName(cartItem.getProductName());
            orderItem.setProductImage(cartItem.getProductImage());
            orderItem.setPrice(BigDecimal.valueOf(cartItem.getProductPrice()));
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setSubtotal(BigDecimal.valueOf(cartItem.getSubtotal()));
            orderItems.add(orderItem);
        }
        // 生成订单号
        order.setOrderNumber(generateOrderNumber());
        
        // 设置订单状态为待支付
        order.setStatus("pending");
        
        // 设置创建时间
        order.setCreateTime(LocalDateTime.now());
        
        // 计算总金额和总数量
        BigDecimal totalAmount = BigDecimal.ZERO;
        int totalQuantity = 0;
        for (OrderItem item : orderItems) {
            totalAmount = totalAmount.add(item.getSubtotal());
            totalQuantity += item.getQuantity();
        }
        order.setTotalAmount(totalAmount);
        order.setTotalQuantity(totalQuantity);
        
        // 插入订单
        orderMapper.insert(order);
        
        // 插入订单项
        for (OrderItem item : orderItems) {
            item.setOrderId(order.getId());
            orderMapper.insertOrderItem(item);
        }
        
        return order;
    }
    
    @Override
    public Order getOrderById(Long id) {
        return orderMapper.findById(id);
    }
    
    @Override
    public Order getOrderByOrderNumber(String orderNumber) {
        return orderMapper.findByOrderNumber(orderNumber);
    }
    
    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        return orderMapper.findByUserId(userId);
    }
    
    @Override
    public List<Order> getOrdersByUserIdAndStatus(Long userId, String status) {
        return orderMapper.findByUserIdAndStatus(userId, status);
    }
    
    @Override
    public boolean updateOrderStatus(Long id, String status) {
        return orderMapper.updateStatus(id, status) > 0;
    }
    
    @Override
    public boolean updateOrderPayment(Long id, String paymentMethod, String paymentId) {
        return orderMapper.updatePayment(id, paymentMethod, paymentId) > 0;
    }
    
    @Override
    public boolean updateOrderTracking(Long id, String trackingNumber) {
        return orderMapper.updateTracking(id, trackingNumber) > 0;
    }
    
    @Override
    public boolean cancelOrder(Long id) {
        return orderMapper.updateStatus(id, "cancelled") > 0;
    }
    
    @Override
    public boolean deleteOrder(Long id) {
        // 先删除订单项
        orderMapper.deleteOrderItemsByOrderId(id);
        // 再删除订单
        return orderMapper.deleteById(id) > 0;
    }
    
    @Override
    public int countOrdersByUserId(Long userId) {
        return orderMapper.countByUserId(userId);
    }
    
    @Override
    public Map<String, Integer> countOrdersByStatus(Long userId) {
        Map<String, Integer> statusCount = new HashMap<>();
        
        // 统计各状态订单数量
        statusCount.put("pending", orderMapper.countByUserIdAndStatus(userId, "pending"));
        statusCount.put("paid", orderMapper.countByUserIdAndStatus(userId, "paid"));
        statusCount.put("shipped", orderMapper.countByUserIdAndStatus(userId, "shipped"));
        statusCount.put("delivered", orderMapper.countByUserIdAndStatus(userId, "delivered"));
        statusCount.put("cancelled", orderMapper.countByUserIdAndStatus(userId, "cancelled"));
        
        return statusCount;
    }
    
    @Override
    public String generateOrderNumber() {
        // 生成格式为：GM + 年月日时分秒 + 4位随机数
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Random random = new Random();
        int randomNum = 1000 + random.nextInt(9000); // 生成1000-9999之间的随机数
        
        return "GM" + dateTime + randomNum;
    }
}